import React from "react"
import GpContainer from "@/components/GpContainer"
import { Search, Popup } from "@taroify/core"
import { Cross, Play } from "@taroify/icons"
import { Swiper, SwiperItem, Image, ScrollView, Navigator, Text, View } from "@tarojs/components"
// import GpPagination from "@/components/GpPagination"
import GpInstitutionItem from "@/components/GpInstitutionItem"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import GpTabbar from "@/components/GpTabbar"
import { /** cloneDeep, **/ dateFormat, setPageMeta } from "@/utils/common"
import clsx from "clsx"
import {
  getRankingInstitution,
  getRankingPageData,
  // getCityInfo,
  getCityPanelData
} from "@/apis/index"
import GpEmpty from "@/components/GpEmpty"
import Taro from "@tarojs/taro"
// import GpIcon from "@/components/GpFontIcon"
import { __CHOOSEDCITY, __LASTLOCATIONAUTHQUERY } from "@/constants/ls"
import { commonUrls } from "@/utils/router"
import ls from "@/utils/ls"
// import { getPosition } from "@/platform/getPosition"
import styles from "./index.module.scss"
import GpScrollLoading from "@/components/GpScrollLoading"

const ports = [{ text: "机构排名" }]
const arrowSize = 20
type IState = {
  pagination: IPagination
  curFilter: number
  /** 榜单推荐 */
  projects: IApiRelative.IGetRankingPageData.IResData["projects"]
  list: IApiRelative.IGetRankingInstitution.IListItem[]
  keyword: string
  hotCitys: IApiRelative.IGetCityPanelData.ICityItem[]
  citys: IApiRelative.IGetCityPanelData.ICity[]
  cityPannelVisible: boolean
  choosedCity: INullable<IApiRelative.IGetCityPanelData.ICityItem>
  showLoading: boolean
}
type IData = {
  filter?: number
  curFilter?: number
  citys: IApiRelative.IGetCityPanelData.ICityItem[]
  pageMeta: {
    region: string
    profession: string
    /** @ignore */
    pageLoaded: boolean
  }
  /** 路径参数 城市id, 如果有，则不需要定位了 */
  city?: string
}
class TrainGuide extends React.Component<unknown, IState> {
  extData: IData
  constructor(props) {
    super(props)
    this.state = {
      pagination: {
        page: 1,
        pageCount: 1
      },
      curFilter: 0,
      projects: [],
      list: [],
      keyword: "",
      hotCitys: [],
      citys: [],
      cityPannelVisible: false,
      choosedCity: {
        cityId: "",
        cityName: "全国"
      },
      showLoading: true
    }
    this.extData = {
      citys: [],
      pageMeta: {
        region: "",
        profession: "",
        pageLoaded: false
      }
    }
  }
  onShareAppMessage() {}
  onLoad(options: Recordable) {
    if (options.filter) {
      this.extData.filter = Number(options.filter)
    }
    if (options.city) {
      this.extData.city = options.city
    }
    this.getPageData().then(() => {
      this.getCitySelectData().then(() => {
        if (this.extData.city) {
          if (this.handleChooseCityFromQuery(true)) {
            return
          }
        }
        // @remark getPageData中已经请求了数据，首次无需再次请求
        // this.tryGetPosition()
      })
    })
  }
  handleChooseCityFromQuery(ignoreSearch: boolean) {
    const validCitys = this.extData.citys || []
    const queryCity = validCitys.find(l => l.cityId == this.extData.city)
    if (queryCity) {
      ls.set(__CHOOSEDCITY, queryCity)
      if (ignoreSearch) {
        this.getPageInfo({
          project: this.extData.curFilter,
          city: queryCity.cityId
        })
      }
      this.setState(
        {
          choosedCity: queryCity
        },
        () => {
          if (ignoreSearch) {
            return
          }
          this.search(1)
        }
      )
      return true
    }
    return false
  }
  componentDidShow() {
    this.setPageInfo()
  }
  setPageInfo = () => {
    const { pageLoaded, region, profession } = this.extData.pageMeta
    if (pageLoaded) {
      setPageMeta({
        keywords: `${region}${profession}艺考机构排行，${region}${profession}艺考机构排名前十`,
        title: `${region}${profession}艺考机构排名前十-${region}${profession}艺考学校排名榜-择艺宝`,
        description: `择艺宝根据平台用户数据浏览，喜欢、报名、点评等大数据分析，帮助学员更好的了解${region}${profession}艺考机构排名前十有哪些，想了解更多${region}${profession}艺考学校排名榜就上择艺宝机构排名查询。`
      })
    }
  }
  getPageInfo = (search: IApiRelative.IGetRankingInstitution.IParams["search"]) => {
    const { choosedCity, projects } = this.state
    if (search.city) {
      this.extData.pageMeta.region = choosedCity?.cityName as string
    } else {
      this.extData.pageMeta.region = "全国"
    }
    if (search.project) {
      const current = projects.find(l => l.value === search.project)
      this.extData.pageMeta.profession = current?.label as string
    } else {
      this.extData.pageMeta.profession = ""
    }
    this.extData.pageMeta.pageLoaded = true
    this.setPageInfo()
  }
  getCitySelectData = () => {
    return getCityPanelData().then(res => {
      if (res.data.success) {
        const retData = res.data.data
        const citys = retData.citys || []
        this.setState({
          hotCitys: retData.hotCitys || [],
          citys
        })
        this.extData.citys = citys.reduce((prev, next) => {
          if (next.childs && next.childs.length > 0) {
            prev.push(...next.childs)
          }
          return prev
        }, [] as IApiRelative.IGetCityPanelData.ICityItem[])
      }
    })
  }
  /** 是否需要再次定位 */
  shouldLocationAuthQuery = (): boolean => {
    const lastQueryDate = ls.get(__LASTLOCATIONAUTHQUERY, null)
    if (lastQueryDate) {
      if (dateFormat() === String(lastQueryDate)) {
        return false
      }
    }
    return true
  }
  fallbackLocation = () => {
    this.setState(
      {
        choosedCity: {
          cityId: "",
          cityName: "全国"
        }
      },
      () => {
        this.search(1)
      }
    )
  }
  locateTip = (title: string) => {
    Taro.hideLoading()
    Taro.showToast({
      title,
      icon: "none"
    })
  }
  currentCityInValidCitys = (currentCity: IApiRelative.IGetCityPanelData.ICityItem) => {
    const validCitys = this.extData.citys
    if (validCitys && validCitys.length > 0) {
      return validCitys.findIndex(l => l.cityId === currentCity.cityId) !== -1
    }
    return false
  }
  tryGetPosition = async () => {
    const choosedCity = ls.get(__CHOOSEDCITY, null)
    if (!choosedCity) {
      if (!this.shouldLocationAuthQuery()) {
        this.fallbackLocation()
        return
      }
      this.fallbackLocation()
      return
      // wip: 【艺考频道】前端暂时屏蔽获取用户定位功能，机构排行页面进入跳转地址默认为“全国”
      // try {
      //   const result: IGetPositionRet = await getPosition()
      //   if (result) {
      //     console.log("result----", result)
      //     const res = await getCityInfo({
      //       cityName: result.cityName,
      //       lat: result.lat,
      //       lng: result.lng,
      //       mapType: result.mapType
      //     })
      //     if (res.data.success) {
      //       this.locateTip("定位成功")
      //       if (this.currentCityInValidCitys(res.data.data)) {
      //         ls.set(__CHOOSEDCITY, res.data.data)
      //         this.setState(
      //           {
      //             choosedCity: res.data.data
      //           },
      //           () => {
      //             this.search(1)
      //           }
      //         )
      //       } else {
      //         console.info("[tryGetPosition] 当前定位城市不在可选城市中")
      //         this.fallbackLocation()
      //       }
      //     } else {
      //       this.locateTip("定位失败")
      //       this.fallbackLocation()
      //     }
      //   }
      // } catch (error) {
      //   this.locateTip("定位失败")
      //   this.fallbackLocation()
      // }
      // this.saveLastLocateAuthQuery()
    } else {
      // this.locateTip("定位成功")
      this.setState(
        {
          choosedCity
        },
        () => {
          this.search(1)
        }
      )
    }
  }
  saveLastLocateAuthQuery = () => {
    ls.set(__LASTLOCATIONAUTHQUERY, dateFormat())
  }
  getPageData = () => {
    const query: IApiRelative.IGetRankingPageData.IParams = {}
    if (this.extData.filter || this.extData.filter === 0) {
      query.project = this.extData.filter
    }
    if (this.extData.city) {
      query.city = this.extData.city
    }
    Taro.showLoading()
    return getRankingPageData(query)
      .then(res => {
        console.log(291, res)
        if (res.data.success) {
          const projects = res.data.data.projects || []
          const curFilter = this.extData.filter ?? projects[0].value
          const retList = res.data.data.list || []
          this.setState({
            projects,
            curFilter,
            list: retList,
            pagination: {
              page: res.data.data.pagination.current,
              pageCount: res.data.data.pagination.pageCount
            },
            showLoading: res.data.data.pagination.current + 1 <= res.data.data.pagination.pageCount
          })
          this.extData.curFilter = curFilter
        }
      })
      .finally(() => {
        Taro.hideLoading()
      })
  }
  search = (page = 1, showLoading = true) => {
    if (showLoading) {
      Taro.showLoading()
    }
    const { choosedCity, list } = this.state
    const search = {
      project: this.extData.curFilter,
      keyword: this.state.keyword
    } as IApiRelative.IGetRankingInstitution.IParams["search"]
    if (choosedCity) {
      search.city = choosedCity.cityId
    }
    this.getPageInfo(search)
    getRankingInstitution({
      search,
      pagination: {
        current: page,
        pageSize: 10
      }
    })
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          const retList = retData.list || []
          this.setState({
            list: page === 1 ? retList : list.concat(retList),
            pagination: {
              page: retData.pagination.current,
              pageCount: retData.pagination.pageCount
            },
            showLoading: retData.pagination.current + 1 <= retData.pagination.pageCount
          })
        }
      })
      .finally(() => {
        if (showLoading) {
          Taro.hideLoading()
        }
      })
  }
  onReachBottom() {
    const { pagination } = this.state
    if (pagination.page + 1 <= pagination.pageCount) {
      this.search(pagination.page + 1, false)
    }
  }
  /** 轮播 */
  renderSwiper = () => {
    return (
      <View className="pb-8px bg-hex-fff">
        <Swiper
          className="h-248px"
          indicatorColor="rgba(255, 255, 255, 0.5)"
          indicatorActiveColor="#FFFFFF"
          circular
          indicatorDots
          autoplay
        >
          <SwiperItem>
            <Navigator
              url={commonUrls.examGuide}
              hoverClass="none"
              className="w-690px h-248px rounded-16px bg-hex-ff0 overflow-hidden mx-auto"
            >
              <Image
                src="https://static.91goodschool.com/UpFiles/public/yikao/image/banner_1.png"
                className="w-690px h-248px"
                mode="aspectFill"
              />
            </Navigator>
          </SwiperItem>
          <SwiperItem>
            <Navigator
              url={commonUrls.institution}
              hoverClass="none"
              className="w-690px h-248px rounded-16px bg-hex-ff0 overflow-hidden mx-auto"
              openType="switchTab"
            >
              <Image
                src="https://static.91goodschool.com/UpFiles/public/yikao/image/banner_2.png"
                className="w-690px h-248px"
                mode="aspectFill"
              />
            </Navigator>
          </SwiperItem>
          <SwiperItem>
            <Navigator
              url={commonUrls.news}
              hoverClass="none"
              className="w-690px h-248px rounded-16px bg-hex-ff0 overflow-hidden mx-auto"
            >
              <Image
                src="https://static.91goodschool.com/UpFiles/public/yikao/image/banner_3.png"
                className="w-690px h-248px"
                mode="aspectFill"
              />
            </Navigator>
          </SwiperItem>
        </Swiper>
      </View>
    )
  }
  // handlePageChange = (page: number) => {
  //   const _pagination = cloneDeep(this.state.pagination)
  //   _pagination.page = page
  //   this.setState(
  //     {
  //       pagination: _pagination
  //     },
  //     () => {
  //       this.search(page)
  //     }
  //   )
  // }
  /** 列表 */
  renderList = () => {
    const { list } = this.state
    console.log(429, list)
    const listLen = list.length
    return (
      <View className="mt-20px bg-hex-fafafd px-30px">
        <View className="flex flex-col">
          {/* item for loop */}
          {listLen > 0 ? (
            list.map((l, index) => (
              <GpInstitutionItem
                key={l.id}
                pureProps={{ institution: l }}
                ranking={{
                  level: l.ranking,
                  levelText: "TOP" + l.ranking
                }}
                className="mb-20px"
                // className={clsx({
                //   "mb-20px": index !== listLen - 1
                // })}
                brandTagline={l.brandTagline ? l.brandTagline : ""}
              />
            ))
          ) : (
            <GpEmpty />
          )}
        </View>
      </View>
    )
  }
  handleTabChange = (item: IApiRelative.IOptional<number>) => {
    const { curFilter } = this.state
    if (curFilter !== item.value) {
      this.setState({
        curFilter: item.value
      })
      this.extData.curFilter = item.value
      this.search(1)
    }
  }
  renderTabs = () => {
    const { curFilter, projects } = this.state
    const len = projects.length
    return (
      <View className="h-90px box-border bg-hex-fff">
        <ScrollView scrollX scrollWithAnimation className="whitespace-nowrap">
          {projects.map((l, index) => (
            <View
              className={clsx(styles["item"], {
                [styles["active"]]: curFilter === l.value,
                [styles["first-child"]]: index === 0,
                [styles["last-child"]]: index === len - 1
              })}
              key={l.value}
              onClick={() => this.handleTabChange(l)}
            >
              {l.label}
              <View className={styles["slider"]}></View>
            </View>
          ))}
        </ScrollView>
      </View>
    )
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className="mt-20px">
        <GpJumpNavs />
      </View>
    )
  }
  handleKeywordChange = (ev: any) => {
    this.setState({
      keyword: ev.detail.value
    })
  }
  openCityPannel = () => {
    this.setState({
      cityPannelVisible: true
    })
  }
  renderFilterArea = () => {
    const { keyword } = this.state
    const choosedCity = this.state.choosedCity
    return (
      <View className="flex flex-row items-center justify-between px-30px box-border">
        <View className="flex items-center flex-none mr-40px" onClick={this.openCityPannel}>
          <Text className="yahei font-normal text-28px text-hex-2c2c35">
            {choosedCity?.cityName || "定位"}
          </Text>
          {/* <GpIcon icon="icon-dingweixianxing" color="#2c2c35" size={34} /> */}
          <View className={styles["locate-icon"]}>
            <Play style={{ color: "#2c2c35" }} size={12} />
          </View>
        </View>
        <View className="flex-1">
          <Search
            className={clsx("top-search__ins_ranking", styles["search-input"])}
            shape="round"
            placeholder="搜索机构"
            value={keyword}
            onChange={this.handleKeywordChange}
            onSearch={() => this.search(1)}
            clearable={false}
          />
        </View>
      </View>
    )
  }
  closeCityPannel = () => {
    this.setState({
      cityPannelVisible: false
    })
  }
  renderCityPannel = () => {
    const { hotCitys, citys, cityPannelVisible, choosedCity } = this.state
    return (
      <Popup
        className={styles["city-popup"]}
        placement="bottom"
        rounded
        open={cityPannelVisible}
        style={{ height: "90%" }}
        onClose={this.closeCityPannel}
      >
        <View className={styles["city-pannel"]} catchMove>
          <View className={styles["pannel-title"]}>
            <View className="yahei-bold font-bold text-32px text-hex-1d2737 text-center relative  box-border py-32px">
              <Cross
                color="#2c2c35"
                style={{
                  fontSize: arrowSize
                }}
                className="absolute right-30px top-28px"
                onClick={this.closeCityPannel}
              />
              选择城市
            </View>
          </View>
          <View className="px-30px mt-8px">
            <View className="text-hex-666 text-20px mb-24px">热门城市</View>
            <View className="grid grid-cols-4 gap-12px">
              {hotCitys.map((l, index) => (
                <View
                  key={index}
                  className={clsx(styles["hot-city"], {
                    [styles["selected-city"]]: l.cityId === choosedCity?.cityId
                  })}
                  onClick={() => this.handleChooseCity(l)}
                >
                  {l.cityName}
                </View>
              ))}
            </View>
          </View>
          <View className="mt-32px">
            {/* item for loop */}
            {citys.map(l => (
              <View key={l.code}>
                <View
                  className="text-hex-999 text-24px px-30px bg-hex-f5f5f5 h-60px leading-60px box-border"
                  id={l.code}
                >
                  {l.code}
                </View>
                <View className="py-16px bg-hex-fff">
                  {l.childs &&
                    l.childs.map(child => (
                      <View
                        className={styles["city-item"]}
                        key={child.cityId}
                        onClick={() => this.handleChooseCity(child)}
                      >
                        {child.cityName}
                      </View>
                    ))}
                </View>
              </View>
            ))}
          </View>
        </View>
      </Popup>
    )
  }
  handleChooseCity = (item: IApiRelative.IGetCityPanelData.ICityItem) => {
    this.setState(
      {
        choosedCity: item,
        cityPannelVisible: false
      },
      () => {
        this.search(1)
      }
    )
  }
  renderTopBg = () => {
    const { choosedCity, curFilter, projects } = this.state
    const filterName = projects.find(l => l.value === curFilter)?.label
    return (
      <View className="w-750px h-248px relative flex justify-center mt-24px">
        <Image
          src="https://static.91goodschool.com/UpFiles/public/yikao/image/bd.png"
          mode="aspectFill"
          className="cover-image w-750px h-248px"
          showLoading
        />
        <View className="relative yahei font-normal text-hex-fff text-54px pt-144px">
          {choosedCity?.cityName}
          {filterName}排行
        </View>
      </View>
    )
  }
  render(): React.ReactNode {
    const { showLoading } = this.state
    return (
      <GpContainer>
        {this.renderCityPannel()}
        <View>
          {/* 轮播 */}
          <View className="pt-20px bg-hex-fff">
            {/* {this.renderSwiper()} */}
            {this.renderFilterArea()}
            {this.renderTopBg()}
            {/* tabs */}
            {this.renderTabs()}
          </View>
          {/* 列表 */}
          {this.renderList()}
          {/* 分液器 */}
          {/* <GpPagination
            onChange={this.handlePageChange}
            pagination={pagination}
            className="mt-20px"
          /> */}
          {showLoading ? (
            <GpScrollLoading />
          ) : (
            <React.Fragment>
              {/* 快捷导航 */}
              {this.renderJumpNavs()}
              {/* 当前位置 */}
              <GpCurrentPort ports={ports} />
            </React.Fragment>
          )}
        </View>
        {/* 底部导航 */}
        <GpTabbar type={15} preserve />
      </GpContainer>
    )
  }
}
export default TrainGuide
